#include <stdio.h>
#define MAXLINE 1000    /* maximum input line size */

int getline(char s[], int lim);
int trim(char s[], int lim);

/* to avoid problems with getline (from the GNU C Library),
   compile using the -std=c99 flag */

/* remove trailing blanks and tabs from line; deletes blank lines */
int main()
{
    int len;            /* current line length */
    char line[MAXLINE];     /* current input line */
    
    while((len = getline(line, MAXLINE)) > 0)
	if(trim(line, len) > 0)
	    printf("%s", line);
    
    return 0;
}

/* getline:  read a line into s, return length */
int getline(char s[], int lim)
{
    int c, i;

    for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
	s[i] = c;
    if(c == '\n'){
	s[i] = c;
	++i;
    }
    s[i] = '\0';
    return i;
}

int trim(char s[], int lim)
{
    int nl=0;

    /* lim is at least 1 */
    if(s[lim-1] == '\n'){
	if(lim == 1)
	    return 0;
	else{
	    lim=lim-2;
	    ++nl;
	}
    }
    else
	--lim;

    for(; lim>=0 && (s[lim] == '\t' || s[lim] == ' '); --lim);
    
    if(nl == 1){
	lim=lim+2;
	if(lim == 1)
	    return 0;
	else
	    s[lim-1]='\n';
    }
    else
	++lim;
    
    s[lim]='\0';

    return lim;
}
